package com.atguigu.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.mapper.DictDao;
import com.atguigu.pojo.Dict;
import com.atguigu.pojo.Permission;
import com.atguigu.pojo.TreeNode;
import com.atguigu.service.DictService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DictServiceImpl /*extends BaseServiceImpl<Dict>*/ implements DictService {

    @Autowired
    DictDao dictDao;

    @Autowired
    JedisPool jedisPool;

    /*@Override
    protected BaseDao<Dict> getEntityDao() {
        return dictDao;
    }*/

    /*
     * [
     * { id:'011',	name:'n1.n1',	isParent:true},
     * { id:'012',	name:'n1.n2',	isParent:false},
     * { id:'013',	name:'n1.n3',	isParent:true},
     * { id:'014',	name:'n1.n4',	isParent:false}
     * ]
     */
    @Override
    public List<Map<String, Object>> findZnodesByParentId(Long id) {
        //根据父节点id查询子节点集合
        List<Dict> childrenList = dictDao.findZnodesByParentId(id);

        List<Map<String, Object>> listData = new ArrayList<Map<String, Object>>();

        //进行数据重新封装
        for (Dict dict : childrenList) {
            Integer count = dictDao.countIsParent(dict.getId());

            Map map = new HashMap();
            map.put("id", dict.getId());
            map.put("name", dict.getName());
            map.put("isParent", count > 0 ? true : false);

            listData.add(map);
        }

        return listData;
    }

    @Override
    public void findAllTree() {
        List<Permission> allTree = dictDao.findAllTree();
        List<TreeNode> treeNodes = new ArrayList<>();

        for (Permission permission : allTree) {
            TreeNode treeNode = new TreeNode();
            treeNode.setId(permission.getId());
            treeNode.setName(permission.getName());
            treeNode.setParentId(permission.getParentId());
            treeNodes.add(treeNode);
            treeNode.setParent(false);
        }
        List<TreeNode> treeNodes1 = streamToTree(treeNodes, "0");
       /* List<Object> result = new ArrayList<>();
        for (TreeNode treeNode : treeNodes) {
            for (TreeNode treeNode2 : treeNodes) {
                if (StringUtils.equals(treeNode2.getParentId().toString(), treeNode.getId().toString())) {
                    treeNode.setParent(true);
                    treeNode.getChildren().add(treeNode2);

                }
            }
            if (treeNode.getParentId() == 0) {
                result.add(treeNode);
            }
        }*/
        System.out.println("allTree = " + allTree);
    }

    public static List<TreeNode> streamToTree(List<TreeNode> treeList, String parentId) {
        List<TreeNode> list = treeList.stream()
                // 过滤父节点
                .filter(parent -> parent.getParentId().toString().equals(parentId))
                // 把父节点children递归赋值成为子节点
                .map(child -> {
                    child.setChildren(streamToTree(treeList, child.getId().toString()));
                    return child;
                }).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<Dict> findListByParentId(Long id) {
        Jedis jedis = jedisPool.getResource();

        List<Dict> list = null;
        try {
            String value = jedis.get("zfw:dict:parentId:" + id); //存储时是字符串类型
            if (!StringUtils.isEmpty(value)) {
                list = JSON.parseObject(value, List.class);
                return list;
            }

            list = dictDao.findZnodesByParentId(id);
            if (!CollectionUtils.isEmpty(list)) {
                jedis.set("zfw:dict:parentId:" + id, JSON.toJSONString(list));
                return list;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
                if (jedis.isConnected()) {
                    try {
                        jedis.disconnect();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return null;
    }

    @Override
    public List<Dict> findListByDictCode(String dictCode) {
        Dict dict = dictDao.findListByDictCode(dictCode);
        if (dict == null) {
            return null;
        }
        return dictDao.findZnodesByParentId(dict.getId());
    }
}
